/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "core/components_ng/pattern/canvas/custom_paint_util.h"
#include "base/utils/string_utils.h"

namespace OHOS::Ace::NG {

// If type is empty or invalid format, use default: "image/png"
std::string GetMimeType(const std::string& type)
{
    // type example: ["image/png"]
    std::string str = type;
    // convert to lowercase string, e.g. "image/png"
    std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { return std::tolower(c); });
    return str;
}

double GetQuality(const std::string& type, const double quality)
{
    // type example: "image/jpeg", quality example: 0.8
    double qua = quality;
    if (type != IMAGE_JPEG && type != IMAGE_WEBP) {
        qua =  DEFAULT_QUALITY;
    }
    if (quality < 0.0 || quality > 1.0) {
        qua =  DEFAULT_QUALITY;
    }
    return qua * QUALITY_COEFFICIENT;
}

#ifndef ACE_UNITTEST
bool EncodeImage(std::string& type, const double quality, SkPixmap& src, SkDynamicMemoryWStream& dst)
{
    bool encodeImageResult = false;
    if (type == IMAGE_JPEG) {
        SkJpegEncoder::Options options;
        options.fQuality = quality;
        encodeImageResult = SkJpegEncoder::Encode(&dst, src, options);
    } else if (type == IMAGE_WEBP) {
        SkWebpEncoder::Options options;
        options.fQuality = quality;
        encodeImageResult = SkWebpEncoder::Encode(&dst, src, options);
    } else {
        type = IMAGE_PNG;
        SkPngEncoder::Options options;
        encodeImageResult = SkPngEncoder::Encode(&dst, src, options);
    }
    return encodeImageResult;
}
#endif
} // namespace OHOS::Ace::NG
